<?php
namespace app\service;
use think\facade\Db;
use app\model\ProductTypeModel;
use Exception;

class ProductTypeService{  
    public function list(){
        $producttypes = ProductTypeModel::where('pid',0)->select(); 
        $tree=[];
        foreach ($producttypes as $types) {
            $tmp=[];
            $tmp['title']=$types['name'].'（'.$types['code'].'）';  
            $tmp['typeName']=$types['name']; 
            $tmp['typeCode']=$types['code']; 
            $tmp['id']=$types['id'];  
            $tmp['pid']=$types['pid'];  
            $tmp['contextmenu']=true;  
            
            $childs = $this->typeChildren($types['id']);
            if($childs){
                $tmp['children']=$childs;
                $tmp['loading']=false;
            }           
            
            $tree[]=$tmp;
        }
        return $tree;
    } 

    public function all(){
        $producttypes = ProductTypeModel::select();        
        return $producttypes;
    } 

    public function typeChildren($pid){
        $producttypes = ProductTypeModel::where('pid',$pid)->select(); 
        $tree=[];
        foreach ($producttypes as $types) {
            $tmp=[];
            $tmp['title']=$types['name'].'（'.$types['code'].'）';  
            $tmp['typeName']=$types['name']; 
            $tmp['typeCode']=$types['code']; 
            $tmp['id']=$types['id'];  
            $tmp['pid']=$types['pid'];  
            $tmp['contextmenu']=true;            
            
            $tree[]=$tmp;
        }
        return $tree;
    } 
    
    public function info($id){
        $producttypes = ProductTypeModel::where('id',$id)->select(); 
        return $producttypes;
    }

    public function save($params){              
        if(empty($params['id'])){
            $data = ProductTypeModel::where('name',$params['name'])->find();
            if($data){
                throw new Exception("分类名称已存在");
            }
            $data = ProductTypeModel::create($params); 
        }else{
            $data = ProductTypeModel::update($params, ['id' => $params['id']]); 
        }        
        return $data;
    }

    public function delete($params){   
        $data = ProductTypeModel::destroy($params['id']);         
        return $data;
    }
}